<template>
	<div class="yuan-container container">
		<a-card title="物料平衡统计">
		
		<a-tabs type="card" @change="tabChange">
			
			<a-tab-pane v-for="(item) in tabsData" :key="item" :tab="item">
			
				<div class="filter-panel">
				<span style="margin-right: 5px;">品名：</span>
				<a-input
				allowClear
				v-model="productName"
				placeholder="请输入品名或批号"
				style="width: 200px; margin-right: 30px;"
				@pressEnter="onSearch"
				/>
				<span style="margin-right: 5px;">批号：</span>
				<a-input
				allowClear
				v-model="batch"
				placeholder="请输入品名或批号"
				style="width: 200px; margin-right: 30px;"
				@pressEnter="onSearch"
				/>
				<!-- <span style="margin-right: 5px;">选择标准类型：</span>
				<a-select
				v-model="searchStandard"
				placeholder="标准类型"
				style="width: 120px; margin-right: 10px;"
				@change="onSearch"
				allow-clear
				>
				<a-select-option value="国标">国标</a-select-option>
				<a-select-option value="省标">省标</a-select-option>
				<a-select-option value="省标-北京">省标-北京</a-select-option>
				<a-select-option value="省标-上海">省标-上海</a-select-option>
				</a-select>
				<span style="margin-right: 5px;">选择日期范围：</span>
				<a-range-picker
				v-model="searchDateRange"
				valueFormat="YYYY-MM-DD"
				style="margin-right: 15px;"
				@change="onSearch"
				:locale="locale"
				/> -->
				<a-button type="primary" @click="onSearch">搜索</a-button>
				<div class="filter-list" style="float: right;margin-right: 0">
				<a-button style="margin-right:5px" type="primary" @click="add">新增</a-button>
				<a-button style="margin-right:5px" @click="downloadTemplate">下载模板</a-button>
				<a-upload
					:show-upload-list="false"
					:before-upload="beforeUpload"
					accept=".xlsx,.xls"
					style="display: inline-block; margin-right: 5px;"
				>
					<a-button>导入数据</a-button>
				</a-upload>
				<a-button type="primary" style="margin-right:0px" @click="exportDataWithType">导出</a-button>
				</div>
			</div>
			<a-table
				:scroll="{ x:  1500 }"
				:loading="tableOption.loading"
				bordered
				:rowKey="item=>item.id"
				:data-source="tableOption.dataSource"
				:columns="tableOption.tableColumns"
				:pagination="tableOption.pagination"
			/>
			</a-tab-pane>
		</a-tabs>
		</a-card>

		<!-- 新增/编辑弹窗 -->
		<AddOrEdit
		:visible.sync="addOrEditVisible"
		:viewDetail="editView"
		:editData="editData"
		:tabName="curTab"
		@success="onAddOrEditSuccess"
		@update:visible="getTableData"
		/>

		<!-- 辅料详情弹窗 -->
		<a-modal
		title="辅料详情"
		:visible="excipientsVisible"
		:footer="null"
		:width="600"
		@cancel="excipientsVisible = false"
		>
		<a-table
			bordered
			:data-source="excipientsData"
			:columns="excipientsColumns"
			:pagination="false"
			:rowKey="item => item.batch || item.name"
		/>
		</a-modal>
	</div>
	</template>

	<script lang="ts">
	import { Vue, Component, Watch } from 'vue-property-decorator'
	import { h, ref } from "vue"
	import locale from "ant-design-vue/lib/date-picker/locale/zh_CN"
	import { UserModule } from "@/store/modules/userModules"
	import AddOrEdit from './components/addOrEdit.vue'
	import nextApi from '@/api/nextApi'
	import { downLoadFile } from '@/utils'


	
	// 导出参数接口
	interface ExportParams {
		name?: string
		batch?: number
		type: string
	}

	@Component({
	name: 'MaterialBalanceStatistics',
	components: {
		AddOrEdit
	}
	})
	export default class MaterialBalanceStatistics extends Vue {
	locale = locale
	productName: string = ''
	batch: string | number = ''
	searchStandard: undefined | string = ''
	searchDateRange: string[] = []
	tabsData: string[] = ['前处理', '提取', '制剂', '包装']
	curTab: string = '前处理'
	
	// 新增/编辑弹窗相关
	addOrEditVisible: boolean = false
	editData: any = {}

	// 辅料详情弹窗
	excipientsVisible: boolean = false
	excipientsData: Array<{ flName: string; flBatch: string; useNum: string }> = []
	excipientsColumns = [
		{ title: '辅料名称', dataIndex: 'flName', key: 'flName', align: 'center' },
		{ title: '辅料批号', dataIndex: 'flBatch', key: 'flBatch', align: 'center' },
		{ title: '使用量', dataIndex: 'useNum', key: 'useNum', align: 'center' }
	]

	// 表格配置
	tableOption: any = {
		loading: false,
		tableColumns: [],
		dataSource: [],
		pagination: {
		pageSize: 10,
		current: 1,
		total: 0,
		showTotal: (total: number) => `共${total}条`,
		onChange: this.pageChange,
		}
	}

	mounted() {
		this.tabChange(this.tabsData[0])
	}
	// 监听toggleCollapsed
	@Watch("state")
	stateChange(n: any) {
		if (n) {
		this.tableOption.width = 1760
		} else {
		this.tableOption.width = 1640
		}
	}

	// 获取vuex中的toggleCollapsed
	get state() {
		return UserModule.toggleCollapsed
	}

	async getTableData() {
		try {
			this.tableOption.loading = true
			// 构建查询参数
			const params:any = {
				page: this.tableOption.pagination.current,
				pageSize: this.tableOption.pagination.pageSize,
				name: this.productName,
				batch: this.batch,
				type: this.getInventoryTypeByTab(this.curTab)
			}
			
			// 调用API
			const response = await nextApi.getMaterialStatisticsList(params)
			
			if (response && response.data) {
				this.tableOption.dataSource = response.data.records
				this.tableOption.pagination.total = response.data.total
				if(this.curTab==='前处理'){
					this.tableOption.dataSource.forEach(item=>{
						if(item.rawBatch){
							item.rawBatch = JSON.parse(item.rawBatch)
						}
					})
				}
			} else {
				this.tableOption.dataSource = []
				this.tableOption.pagination.total = 0
			}
			console.log(this.tableOption.dataSource);
			
		} catch (error) {
			console.error('获取数据失败:', error)
			this.$message.error('获取数据失败')
			this.tableOption.dataSource = []
			this.tableOption.pagination.total = 0
		} finally {
			this.tableOption.loading = false
		}
	}



	pageChange(page: number, pageSize: number) {
		this.tableOption.pagination.current = page
		this.getTableData()
	}

	/**
	 * @description tab切换
	 **/
	tabChange(e: string) {
		this.curTab = e
		this.changeColumn()
		this.getTableData()
	}

	changeColumn() {
	switch (this.curTab) {
		case '前处理':
			this.tableOption.tableColumns = [
			{
				title: "序号",
				dataIndex: "index",
				key: "index",
				align: "center",
				width: 60,
				customRender: (text: string, record: any, index: number) => index + 1
			},
			{
				title: "品名",
				dataIndex: "name",
				key: "name",
				align: "center",
				width: 120,
				customRender:(text:string,record:any)=>{
					if(!record.name)return '-'
					return record.name.substring(0,record.name.length-4)
				}
			},
			{
				title: "标准类型",
				dataIndex: "standard",
				key: "standard",
				align: "center",
				width: 100
			},
			{
				title: "前处理批号",
				dataIndex: "batch",
				key: "batch",
				align: "center",
				width: 150
			},
			{
				title: "药材来料批号",
				dataIndex: "rawBatch",
				key: "rawBatch",
				align: "center",
				width: 150,
				customRender:(text:string,record:any)=>{
					if(!record.rawBatch)return '-'
					let arr = JSON.parse(record.rawBatch).map(item=>{
						return item
					})
					return arr.join(',')
				}
			},
			{
				title: "药材领用量",
				dataIndex: "takeNum",
				key: "takeNum",
				align: "center",
				width: 150,
				customRender:(text:string,record:any)=>{
					if(!record.takeNum)return '-'
					let arr = JSON.parse(record.takeNum).map(item=>{
						return item
					})
					return arr.join(',')
				}
				
			},
			{
				title: "药材报告日期",
				dataIndex: "reportDate",
				key: "reportDate",
				align: "center",
				width: 150,
				customRender:(text:string,record:any)=>{
					if(!record.reportDate)return '-'
					let arr = JSON.parse(record.reportDate).map(item=>{
						return item
					})
					return arr.join(',')
				}
			},
			{
				title: "药材领用日期",
				dataIndex: "takeDate",
				key: "takeDate",
				align: "center",
				width: 150,
				customRender:(text:string,record:any)=>{
					if(!record.takeDate)return '-'
					
					let arr = JSON.parse(record.takeDate).map(item=>{
						return item
					})
					return arr.join(',')
				}
			},
			{
				title: "药材领用与报告时间逻辑判定",
				dataIndex: "logic",
				key: "logic",
				align: "center",
				width: 180,
				customRender:(text:string,record:any)=>{
					if(!record.logic)return '-'
					let arr = JSON.parse(record.logic).map(item=>{
						return item
					})
					return arr.join(',')
				}
			},
			{
				title: "饮片产出量",
				dataIndex: "prodNum",
				key: "prodNum",
				align: "center",
				width: 120
			},
			{
				title: "饮片生产结束日期",
				dataIndex: "prodEndDate",
				key: "prodEndDate",
				align: "center",
				width: 140
			},
			{
				title: "饮片产出与提取投料平衡判定",
				dataIndex: "balance",
				key: "balance",
				align: "center",
				width: 180
			},
			{
				title: "辅料",
				dataIndex: "flList",
				key: "flList",
				align: "center",
				width: 80,
				fixed: 'right',
				customRender: (text: string, record: any) => {
				return h('a', {
					style: { color: '#1890ff', cursor: 'pointer' },
					on: {
					click: () => this.handleExcipientsDetail(record)
					}
				}, '详情')
				}
			},
			{
				title: "操作",
				key: "action",
				align: "center",
				width: 80,
				fixed: 'right',
				customRender:(text:string,record:any)=>{
					return h("a",{
							style: { color: '#1890ff', cursor: 'pointer' },
							on: { click: () => this.handleEdit(record) },
					},"编辑");
				}
				
			}
			]
			break
		case '提取':
			this.tableOption.tableColumns = [
			{
				title: "序号",
				dataIndex: "index",
				key: "index",
				align: "center",
				width: 60,
				customRender: (text: string, record: any, index: number) => index + 1
			},
			{
				title: "品名",
				dataIndex: "name",
				key: "name",
				align: "center",
				width: 120,
				customRender:(text:string,record:any)=>{
					if(!record.name)return '-'
					//返回除最后四位以外的所有字符
					return record.name.substring(0,record.name.length-3)
				}
			},
			{
				title: "标准类型",
				dataIndex: "standard",
				key: "standard",
				align: "center",
				width: 100
			},
			{
				title: "提取批号",
				dataIndex: "batch",
				key: "batch",
				align: "center",
				width: 150
			},
			{
				title: "提取来料饮片批号",
				dataIndex: "rawBatch",
				key: "rawBatch",
				align: "center",
				width: 150,
			},
			{
				title: "提取投料量",
				dataIndex: "inputNum",
				key: "inputNum",
				align: "center",
				width: 120
			},
			{
				title: "提取领用日期",
				dataIndex: "takeDate",
				key: "takeDate",
				align: "center",
				width: 120
			},
			{
				title: "饮片产出与提取领用时间逻辑判定",
				dataIndex: "logic",
				key: "logic",
				align: "center",
				width: 180
			},
			{
				title: "收粉浸膏粉产出量",
				dataIndex: "sfProdNum",
				key: "sfProdNum",
				align: "center",
				width: 120
			},
			{
				title: "过筛浸膏粉产出量",
				dataIndex: "gsProdNum",
				key: "gsProdNum",
				align: "center",
				width: 120
			},
			{
				title: "混一浸膏粉产出量",
				dataIndex: "hyProdNum",
				key: "hyProdNum",
				align: "center",
				width: 120
			},
			{
				title: "混一结束日期",
				dataIndex: "prodEndDate",
				key: "prodEndDate",
				align: "center",
				width: 140
			},
			{
				title: "混一产出与混二投入物料平衡判定",
				dataIndex: "balance",
				key: "balance",
				align: "center",
				width: 180
			},
			{
				title: "操作",
				key: "action",
				align: "center",
				width: 80,
				fixed: 'right',
				customRender: (text: string, record: any) => {
				return h('a', {
					style: { color: '#1890ff', cursor: 'pointer' },
					on: {
					click: () => this.handleEdit(record)
					}
				}, '编辑')
				}
			}
			]
			break
		case '制剂':
			this.tableOption.tableColumns = [
			{
				title: "序号",
				dataIndex: "index",
				key: "index",
				align: "center",
				width: 60,
				customRender: (text: string, record: any, index: number) => index + 1
			},
			{
				title: "品名",
				dataIndex: "name",
				key: "name",
				align: "center",
				width: 120,
				customRender:(text:string,record:any)=>{
					if(!record.name)return '-'
					return record.name.substring(0,record.name.length-8)
				}
			},
			{
				title: "标准类型",
				dataIndex: "standard",
				key: "standard",
				align: "center",
				width: 100
			},
			{
				title: "制剂批号",
				dataIndex: "batch",
				key: "batch",
				align: "center",
				width: 150
			},
			{
				title: "制剂来料提取批号",
				dataIndex: "rawBatch",
				key: "rawBatch",
				align: "center",
				width: 180,
			},
			{
				title: "混二领用量",
				dataIndex: "takeNum",
				key: "takeNum",
				align: "center",
				width: 120
			},
			{
				title: "混二领用日期",
				dataIndex: "takeDate",
				key: "takeDate",
				align: "center",
				width: 140
			},
			{
				title: "混二产出量",
				dataIndex: "prodNum",
				key: "prodNum",
				align: "center",
				width: 120
			},
			{
				title: "颗粒产出量",
				dataIndex: "klProdNum",
				key: "klProdNum",
				align: "center",
				width: 120
			},
			{
				title: "颗粒生产结束日期",
				dataIndex: "prodEndDate",
				key: "prodEndDate",
				align: "center",
				width: 160
			},
			{
				title: "分装领用量与制粒产出量物料平衡判定",
				dataIndex: "balance",
				key: "balance",
				align: "center",
			},
			{
				title: "操作",
				key: "action",
				align: "center",
				width: 80,
				fixed: 'right',
				customRender: (text: string, record: any) => {
				return h('a', {
					style: { color: '#1890ff', cursor: 'pointer' },
					on: {
					click: () => this.handleEdit(record)
					}
				}, '编辑')
				}
			}
			]
			break
		case '包装':
			this.tableOption.tableColumns = [
			{
				title: "序号",
				dataIndex: "index",
				key: "index",
				align: "center",
				width: 60,
				customRender: (text: string, record: any, index: number) => index + 1
			},
			{
				title: "品名",
				dataIndex: "name",
				key: "name",
				align: "center",
				width: 120,
				customRender:(text:string,record:any)=>{
					if(!record.name)return '-'
					return record.name.substring(0,record.name.length-4)
				}
			},
			{
				title: "标准类型",
				dataIndex: "standard",
				key: "standard",
				align: "center",
				width: 100
			},
			{
				title: "产品大类",
				dataIndex: "inventoryType",
				key: "inventoryType",
				align: "center",
				width: 100
			},
			{
				title: "包装批号",
				dataIndex: "batch",
				key: "batch",
				align: "center",
				width: 120
			},
			{
				title: "分装颗粒来料批号",
				dataIndex: "rawBatch",
				key: "rawBatch",
				align: "center",
				width: 180,
			},
			{
				title: "分装领用日期",
				dataIndex: "takeDate",
				key: "takeDate",
				align: "center",
				width: 140
			},
			{
				title: "制粒结束时间与分装领用时间逻辑判定",
				dataIndex: "logic",
				key: "logic",
				align: "center",
				width: 220
			},
			{
				title: "颗粒使用量",
				dataIndex: "klUseNum",
				key: "klUseNum",
				align: "center",
				width: 120
			},
			{
				title: "分装颗粒领用量",
				dataIndex: "takeNum",
				key: "takeNum",
				align: "center",
				width: 150
			},
			{
				title: "颗粒退库量",
				dataIndex: "klBackNum",
				key: "klBackNum",
				align: "center",
				width: 120
			},
			{
				title: "成品产出量",
				dataIndex: "prodNum",
				key: "prodNum",
				align: "center",
				width: 120
			},
			{
				title: "包装结束日期",
				dataIndex: "prodEndDate",
				key: "prodEndDate",
				align: "center",
				width: 140
			},
			{
				title: "操作",
				key: "action",
				align: "center",
				width: 80,
				fixed: 'right',
				customRender: (text: string, record: any,index:number) => {				
				return h('a', {
					style: { color: '#1890ff', cursor: 'pointer' },
					on: {
					click: () => this.handleEdit(record)
					}
				}, '编辑')
				}
			}
			]
			break
		}
	}

	onSearch() {
		this.tableOption.pagination.current = 1
		this.getTableData()
	}

	exportData() {
		this.exportDataWithType()
	}

	async exportDataWithType() {
		try {
			// 检查是否有数据可以导出
			if (this.tableOption.dataSource.length === 0) {
				this.$message.warning('暂无数据可导出')
				return
			}
			
			this.$message.loading('正在导出数据...', 0)
			// 调用导出API
			await nextApi.exportMaterialStatistics({name:this.productName,batch:this.batch,type:this.curTab}, (response:any) => {
				const blob = new Blob([response.data],{
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
				})
				downLoadFile(blob,`物料平衡统计表_${this.curTab}_${new Date().toISOString().slice(0, 10)}.xlsx`)
				this.$message.destroy()
				this.$message.success('导出成功')
			})
		} catch (error) {
			this.$message.destroy()
			console.error('导出失败:', error)
			this.$message.error('导出失败，请重试')
		}
	}

	add() {
			this.editData = {}
			this.addOrEditVisible = true
			this.editView = false
	}
	editView = false
	handleEdit(record: any) {
			this.editData = record
			this.addOrEditVisible = true
			this.editView = true
	}

	handleExcipientsDetail(record: any) {
		this.excipientsData = record.flList
		this.excipientsVisible = true
	}

	// 根据tab获取对应的inventoryType
	getInventoryTypeByTab(tab: string): string {
		switch (tab) {
			case '前处理':
				return '前处理'
			case '提取':
				return '提取'
			case '制剂':
				return '制剂'
			case '包装':
				return '包装'
			default:
				return ''
		}
	}

	// 下载模板
	async downloadTemplate() {
		try {
			this.$message.loading('正在下载模板...', 0)
			// 调用下载模板API
			await nextApi.exportMaterialStatisticsTemplate({type: this.curTab}, (response: any) => {
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
				})
				downLoadFile(blob, `物料平衡统计模板_${this.curTab}_${new Date().toISOString().slice(0, 10)}.xlsx`)
				this.$message.destroy()
				this.$message.success('模板下载成功')
			})
		} catch (error) {
			this.$message.destroy()
			console.error('下载模板失败:', error)
			this.$message.error('下载模板失败，请重试')
		}
	}

	// 导入数据前的处理
	beforeUpload(file: File) {
		const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
						file.type === 'application/vnd.ms-excel'
		if (!isExcel) {
			this.$message.error('只能上传Excel文件！')
			return false
		}
		const isLt10M = file.size / 1024 / 1024 < 10
		if (!isLt10M) {
			this.$message.error('文件大小不能超过10MB！')
			return false
		}
		this.importData(file)
		return false // 阻止自动上传
	}

	// 导入数据
	async importData(file: File) {
		try {
			this.$message.loading('正在导入数据...', 0)
			
			const formData = new FormData()
			formData.append('file', file)
			formData.append('type', this.curTab)
			
			const response = await nextApi.importMaterialStatistics(formData)
			
			this.$message.destroy()
			if (response && response.code === 200) {
				this.$message.success('数据导入成功')
				this.getTableData() // 刷新表格数据
			} else {
				this.$message.error(response?.message || '导入失败')
			}
		} catch (error) {
			this.$message.destroy()
			console.error('导入数据失败:', error)
			this.$message.error('导入数据失败，请重试')
		}
	}

	// 新增/编辑成功回调
	onAddOrEditSuccess() {
		this.getTableData()
	}
	}
	</script>

	<style lang="scss" scoped>
	.yuan-container {
	.filter-panel {
		padding: 0px;
		.filter-list {
		margin-top: 10px;
		}
	}

	.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab {
		background: #fafafa;
		border-color: #d9d9d9;
		
		&.ant-tabs-tab-active {
		background: #fff;
		border-bottom-color: #fff;
		}
	}

	.ant-table {
		.ant-table-thead > tr > th {
		background-color: #fafafa;
		font-weight: 600;
		}
	}
	}

	// 响应式设计
	@media (max-width: 768px) {
	.yuan-container {
		padding: 10px;

		.filter-panel {
		.filter-list {
			float: none !important;
			margin-top: 15px;
			text-align: center;
		}
		}
	}
	}
	</style>
